<?php
class StateModel extends CI_Model
{
    // Mongo
    const collection = 'state';
    const sequence_id = 'state';

    // Cache
    const cache_enable = true;
    const cache_ttl = 86400;
    const prefix_cache_item = 'state.%s';
    const prefix_cache_list = 'state.list.%s';
    const prefix_cache_count = 'state.count.%s';

    public function  __construct()
    {
        parent::__construct();
    }

    public function selectState($id)
    {
        if(empty($id)) return false;

        $data = false;
        
        // Cache key
        $cacheKey = sprintf(self::prefix_cache_item, $id);

        // Read cache
        if(self::cache_enable) {
            $this->cache->memcached->get($cacheKey);
        }

        // Check cache
        if($data === false) {

            // Get from DB
            $data = $this->mongo_db->where(array('_id' => $id))->getOne(self::collection);

            // Write to cache
            $this->cache->memcached->save($cacheKey, $data, 0, self::cache_ttl);
        }

        // Return
        return $data;
    }

    public function selectStateList()
    { 
        $list = false;

        // Create cache key
        $cacheKey = sprintf(self::prefix_cache_list, 'all');

        // Check cache
        if(self::cache_enable) {
            // Get cache
            $list = $this->cache->memcached->get($cacheKey);
        }

        // Check cache 
        if($list === false) {

            // Get from Db
            $list = $this->mongo_db->order_by(array('_id' => 1))->get(self::collection);

            // Json decoder
            if(is_array($list)) {
                foreach($list as &$item) {
                    $item['params'] = json_decode($item['params']);
                }
            }

            // Write to cache
            $this->cache->memcached->save($cacheKey, $list, 0, self::cache_ttl);
        }

        // Return
        return $list;
    }

    public function selectTotalState()
    {
        $total = false;

        // Create cache key
        $cacheKey = sprintf(self::prefix_cache_count, 'all');

        // Get cache
        if(self::cache_enable) {
            $total = $this->cache->memcached->get($cacheKey);
        }

        // Check cache
        if($total === false) {

            // Get CI
            $CI = &get_instance();

            // Load model
            $CI->load->model('SequenceModel');

            // Get total from DB
            $total = $CI->SequenceModel->getSequence(self::sequence_id);

            // Write to cache
            $this->cache->memcached->save($cacheKey, $total, 0, self::cache_ttl);
        }

        // Return
        return $total;
    }
}